import { useCallback, useEffect, useState } from "react";
import { Select } from "antd";
import { cloneDeep } from "lodash";

export const useSizeList = ({ dataSource, setDataSource, Separator, skuSizeList, colorDataSource, selectOptionsMap }) => {
	useEffect(() => {
		setDataSource(
			skuSizeList.map(e => {
				return {
					...e,
					sysSpecs: e.specs
				};
			})
		);
	}, [skuSizeList]);

	const handleChange = useCallback((size, record, index, colorDataSourceRow) => {
		const { matchStore, sysColor, skuId, specs, spuId } = colorDataSourceRow;
		const { storeId, storeName, storeSpuId, storeSpuName, storeColor } = matchStore;

		const code = `${storeId}${Separator}${storeSpuId}`;

		setDataSource(pre => {
			const __pre = cloneDeep(pre);
			__pre.forEach(p => {
				if (p.sysSpecs == record.sysSpecs) {
					p[code] = size;
				}
			});
			return __pre;
		});
	}, []);

	const [columns, setColumns] = useState([]);
	useEffect(() => {
		const arr = [
			{
				name: "尺码",
				code: "sysSpecs",
				width: "20%"
			}
		];
		colorDataSource
			.filter(e => e.storeColor)
			.forEach(e => {
				const { matchStore, sysColor, skuId, specs, spuId } = e;
				const { storeId, storeName, storeSpuId, storeSpuName, storeColor } = matchStore;
				const code = `${storeId}${Separator}${storeSpuId}`;
				const options = selectOptionsMap[code] || [];
				const f = arr.find(ee => ee.code === code);
				if (!f) {
					arr.push({
						name: `${storeName}（商品编码${storeSpuId}）`,
						code: code,
						width: 200,
						render: (v, record, index) => {
							return (
								<Select
									allowClear
									className="width-full"
									value={v}
									onChange={size => {
										handleChange(size, record, index, e);
									}}
									options={options.map(e => ({ value: e, label: e }))}
								/>
							);
						}
					});
				}
			});
		setColumns(arr);
	}, [colorDataSource]);

	const tableKey = "SystemGoodsMatchSeniorMatchTableSize";

	const searchSimpleTableProps = {
		tableKey,
		rowKey: "uuid",
		// ///
		dataSource,
		columns,
		footer: false
	};
	return {
		tableKey,
		searchSimpleTableProps,
		dataSource
	};
};
